<?php

namespace app\api\controller\wanlshop;

use app\api\model\wanlshop\Goods;
use app\api\model\wanlshop\Order as orderModel;
use app\api\model\wanlshop\OrderGoods;
use app\api\service\wanlshop\GoodsSku;
use app\common\controller\Api;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\Request;
use app\api\model\wanlshop\Pay;

class Buyback extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    // 订单模块Model
    protected $orderModel = null;

    // 订单商品模块Model
    protected $orderGoodsModel = null;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->orderModel = new orderModel();
        $this->orderGoodsModel = new OrderGoods();
    }

    /**
     * 回购列表
     * @return void
     * @throws DbException
     * @throws Exception
     */
    public function list()
    {
        $this->request->filter(['strip_tags']);

        $uid = $this->auth->id;
//        $uid = 3;

        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get("pageSize", 10);

        $where["order.user_id"] = $uid;
        $where["order.order_type"] = ['>', 0];

        // 回购记录
        $count = $this->orderModel
            ->alias('order')
            ->with(['orderItem' => function ($query) {
                $query->where('type', 'new');
            }, 'shop'])
            ->where($where)
            ->count();
        // 数据
        $list = $this->orderModel
            ->alias('order')
            ->where($where)
            ->with(['orderItem' => function ($query) {
                $query->where('type', 'new')->with(['goodsItem' => function ($query) {
                    $query->withField('id,platform');
                }]);
            }, 'shop'])
            ->order("order.updatetime desc")
            ->paginate($pageSize, $count, ['page' => $page])
            ->each(function ($item) {
                $item->shop = $item->shop ?: new \stdClass();
                return $item;
            })
            ->toArray();
        $this->success("成功", $list, 1);
    }

    /**
     * 换购详情
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function detail()
    {
        $order_id = $this->request->get('order_id', 0);
        $detail = $this->orderModel
            ->with([
                'orderItem' => function ($query) {
                    $query->with(['goodsItem' => function ($query) {
                        $query->withField(['id', 'platform']);
                    }]);
                },
                'shop' => function ($query) {
                    $query->withField(['id', 'shopname', 'return']);
                },
                'pay'
            ])
            ->where('id', $order_id)
            ->find();
        $detail['shop'] = $detail['shop'] ?: new \stdClass();
        $detail['createtime'] = date('Y-m-d H:i:s', $detail['createtime']);
        $this->success("成功", $detail, 1);
    }

    /**
     * 可换购商品列表
     * @return void
     * @throws DbException
     * @throws Exception
     */
    public function goods()
    {
        $pageSize = $this->request->request("pageSize", 10);
        $page = $this->request->request("page", 1);
        $from = $this->request->request('from', 'list');

        // 订单为已支付的.没有使用积分的.普通订单.没有使用过优惠券的
        //列表页，支付完就显示，换购详情选择商品页，确认收货才显示，过了七天无理由才可以换购
        $uid = $this->auth->id;
        //订单状态:1=待支付,2=待发货,3=待收货,4=待评论,5=售后订单(已退款),6=已完成,7=已取消,8-待审核,9-已拒绝,10-退款中
        $state = $from == 'list' ? ['in', [2, 3, 4, 10, 6]] : ['in', [4, 6]];
        $where = [
            'order.user_id' => $uid,
            'order.state' => $state,
            'order.status' => $this->orderModel->statusForSpecific[0],//normal
//            'order.score' => 0,//积分
//            'order.coupon_id' => 0,//优惠券
//            'goods.is_buyback' => '0',//没换购
//            'goods.is_withdraw' => '0',//没提现
            'goods.type' => 'new', //新商品
        ];

        // 订单列表
        $count = $this->orderGoodsModel
            ->alias('goods')
            ->join('fa_wanlshop_order order', 'order.id = goods.order_id', 'left')
            ->where($where)
            ->count();

        $lists = $this->orderGoodsModel
            ->alias('goods')
            ->field("order.*,goods.id as goods_model_id,goods.*")
            ->join('fa_wanlshop_order order', 'order.id = goods.order_id', 'left')
            ->where($where)
            ->order("order.createtime desc")
            ->paginate($pageSize, $count, ['page' => $page])
            ->each(function ($item) use ($uid) {
                $item->shop = \app\admin\model\wanlshop\Shop::where('id', $item->shop_id)->field('id,shopname,return,isself,user_id')->find();
                $item->order_item = $this->orderGoodsModel->where('id', $item->goods_model_id)->select();
                $item->fullayment = Pay::isFullayment($item->order_id, $uid);
                return $item;
            })
            ->toArray();

        // 库存入缓存
        $goodsSkuService = new GoodsSku();
        foreach ($lists['data'] as $key => $val) {
            $dict = Goods::where('id', 'in', array_column($val['order_item'], 'goods_id'))->column('id,title,platform', 'id');
            $types = array_unique(OrderGoods::where('order_id', $val['order_id'])->column('type'));


            // if ($val['id'] == 348) {
            //     dd($val['taketime']  > time() + 7 * 86400);
            // }
            //是否超过7天无理由
            $is_overtime = $val['taketime'] > 0 && ($val['taketime'] + 7 * 86400 < time());
            $lists['data'][$key]['is_overtime'] = intval($is_overtime);
            $lists['data'][$key]['order_type_text'] = orderModel::getOrderType($val['order_id']);
            foreach ($val['order_item'] as $k => $item) {
                //$goodsSkuService->addStockToCache($item['goods_sku_id']);
                //过7天无理由退货,全款购买的(没有使用优惠券，旧件，积分，没有使用过提现换购)，才可提现
                //过7天无理由退货，没有使用过提现换购,可以换购
                //使用发票的，线下的，不可提现只可换购
                $can_buyback = $can_withdraw = 1;
                if ($item['is_buyback'] == 1 || $item['is_withdraw'] == 1 || !in_array($val['state'], [4, 6]) || in_array('old', $types) ||
                    $val['order_type'] == 2 || $val['invoice_id'] > 0 || $val['offline_order'] == 1 || $val['fullayment'] == 0) {
                    $can_withdraw = 0;
                }

                if ($item['is_buyback'] == 1 || $item['is_withdraw'] == 1 || !in_array($val['state'], [4, 6])) {
                    $can_buyback = 0;
                }
                //全款买的即能提现又能换购，两者各可使用一次
                if ($val['fullayment'] == 1 && $val['offline_order'] == 0 && $val['invoice_id'] == 0) {
                    if ($item['is_buyback'] == 0) {
                        $can_buyback = 1;
                    }
                    if ($item['is_withdraw'] == 0) {
                        $can_withdraw = 1;
                    }
                }
                $lists['data'][$key]['order_item'][$k]['platform'] = $dict[$item['goods_id']]['platform'] ?? 0;
                $lists['data'][$key]['order_item'][$k]['can_buyback'] = $can_buyback;
                $lists['data'][$key]['order_item'][$k]['can_withdraw'] = $can_withdraw;
            }
        }
        $this->success("成功", $lists, 1);
    }
}